/*
 * name:延迟可用按钮 TimeoutBtn
 * author:yanmu.wj@taobao.com
 * date:2011-11-23
 */
KISSY.add('TimeoutBtn',function(S){
    var TimeoutBtn = function(cfg){
        this.btn = cfg.btn && S.one(cfg.btn);
        this.time = cfg.time ? (Number(cfg.time) || 0) : 0;
        this.disabledCls = cfg.disabledCls || '';
        this.format = cfg.format || '%t%秒后可重新操作';

        this.btnText = this.btn ? this.btn.text() : '';

        this._id = 0;
    };
    var _TimeoutBtn = function(cfg){
        return new TimeoutBtn(cfg);
    };
    S.augment(TimeoutBtn,{
        _counter:0,
        start:function(){
            if(!this.btn || !this.time) return;

            this.btn.prop('disabled',true);
            this.refresh();
            var self = this;

            if(this._id) window.clearInterval(this._id);
            this._id = setInterval(function(){self.disabled();},1000);
        },
        disabled:function(){
            this._counter++;

            if(this._counter == this.time){
                this.clear();
            }else{
                this.refresh();
            }
        },
        clear:function(){
            window.clearInterval(this._id);
            this._id = '';
            this._counter = 0;
            this.btn.prop('disabled',false);
            this.btn.text(this.btnText);
            if(this.disabledCls) this.btn.removeClass(this.disabledCls);
        },
        refresh:function(){
            this.btn.text(this.format.replace('%t%',this.time-this._counter));
            if(this.disabledCls) this.btn.addClass(this.disabledCls);
        }
    });

    return _TimeoutBtn;
});
